﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Golos.Helper;
using Golos.Users.UserCache;

namespace Golos.Polls.Http
{
    public partial class PollCacheServer
    {
        private void GetDistribution(HttpListenerContext context, ref int statusCode)
        {
            try
            {
                if (context.Request.QueryString.AllKeys.Contains("questionid") && context.Request.QueryString.AllKeys.Contains("type"))
                {
                    Guid questionId = new Guid(context.Request.QueryString["questionid"]);
                    string distributionType = context.Request.QueryString["type"];
                    byte[] data = new byte[0];
                    switch (distributionType.ToUpperInvariant())
                    {
                        case "SOCIALWEB":
                            Dictionary<UserIdType, int> result = pollCache.GetDistributionBySocialweb(questionId);
                            if (result.Count > 0)
                                using (MemoryStream stream = new MemoryStream())
                                {
                                    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                                    {
                                        foreach (UserIdType userIdType in result.Keys)
                                        {
                                            writer.WriteLine(string.Format("{0}\t{1}", userIdType, result[userIdType]));
                                        }
                                        writer.Flush();
                                    }
                                    data = stream.ToArray();
                                }
                            break;
                        default:
                            statusCode = (int)HttpStatusCode.BadRequest;
                            return;
                    }
                    context.Response.ContentLength64 = data.LongLength;
                    context.Response.ContentEncoding = Encoding.Default;
                    context.Response.OutputStream.Write(data, 0, data.Length);
                    statusCode = (int)HttpStatusCode.OK;
                    return;
                }
                statusCode = (int)HttpStatusCode.BadRequest;
            }
            catch (Exception exception)
            {
                LogClass.WriteErrorEntry(exception.ToString());
                statusCode = (int)HttpStatusCode.InternalServerError;
            }
        }
    }
}
